<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ajax练习数据遍历过滤</title>
</head>
<body>

  <button id="btn">搜索</button>
  <div class="selectJob">
    <input type="radio" name="job" value="all" checked>所有
  <input type="radio" name="job" value="fighter">战士
  <input type="radio" name="job" value="mage">法师
  <input type="radio" name="job" value="assassin">刺客
  <input type="radio" name="job" value="tank">坦克
  <input type="radio" name="job" value="marksman">射手
  <input type="radio" name="job" value="support">辅助
  </div>
  
  <div id="show"></div>
  <script type="text/javascript">
  let btn = document.querySelector('#btn')
    // 全局存放英雄信息  
  let hero = null;

  //单击获取数据
  btn.onclick=function(){
    // 准备请求的地址
    let url = 'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js?v=19'


    let xhr = new XMLHttpRequest()
    xhr.onloadend = function(){
      let data = JSON.parse(xhr.response)
      hero = data.hero
      showTable(hero)
    }
    xhr.open('get',url)
    xhr.send()
  }
  btn.onclick()
  // 显示数据到表格
  function showTable (hero){

    let free=['否','是']

    let job={
      mage:'法师',
      fighter:'战士',
      tank:'坦克',
      assassin:'刺客',
      support:'辅助',
      marksman:'射手'
    }
    // 图片相同部分头，后续拼接人物英文名+.png
    let face = 'https://game.gtimg.cn/images/lol/act/img/champion/'
    
    let str = `<table border=1 width="900px">
      <tr>
        <th>编号</th>
        <th>称号</th>
        <th>头像</th>
        <th>英文名</th>
        <th>名称</th>
        <th>角色</th>
        <th>攻击</th>
        <th>防御</th>
        <th>魔法</th>
        <th>上手难度</th>
        <th>周免费</th>
        </tr>`
        str += hero.map(item=>`<tr>
        <td>${item.heroId}</td>
        <td>${item.name}</td>
        <td>
          <img src="${face+item.alias +'.png'}" alt="" />
          </td>
        <td>${item.alias}</td>
        <td>${item.title}</td>
        <td>${item.roles.map(item=>job[item])}</td>
        <td>${item.attack}</td>
        <td>${item.defense}</td>
        <td>${item.magic}</td>
        <td>${item.difficulty}</td>
        <td>${free[item.isWeekFree]}</td>
        </tr>`
        ).join('')
      str +='</table>';

      let show = document.querySelector('#show')
      show.innerHTML = str
  }

  // 战士
  let selectJob=document.querySelector('.selectJob')
  selectJob.onclick=function(e){
    if (e.target.localName === 'input'){
      // 获取点击的职业名称
      let job=e.target.value;
      let filter_hero = hero.filter(item=>item.roles.includes(job))

      // 如果是all就返回去全部
      if(job==='all'){
        filter_hero = hero
      }
      showTable(filter_hero)
    }
  }
  </script>
</body>
</html>